package com.basker.pisces.domain.element.serialize.xml;

import java.util.Map;

import org.springframework.util.Assert;

import com.basker.pisces.core.meta.IDataObjectMeta;
import com.basker.pisces.core.meta.bean.BeanMetaManager;
import com.basker.pisces.core.serialize.xml.AbstractXmlSerializeHandler;
import com.basker.pisces.domain.element.meta.ElementType;
import com.basker.pisces.domain.element.meta.MetaType;
import com.basker.pisces.utils.ClassUtils;

public class MetaTypeXmlSerializeHandler extends AbstractXmlSerializeHandler {

    private MetaType metaType;

    public MetaTypeXmlSerializeHandler(MetaType metaType) {
        Assert.notNull(metaType, "parameter 'metaType' is required");

        this.metaType = metaType;
    }

    @Override
    public IDataObjectMeta getDataObjectMeta(String name, Map<String, String> attrs) {
        Assert.hasText(name, "parameter 'name' is required");

        if (writeClassName()) {
            String typeName = attrs.get("type");

            Assert.hasText(typeName, "attr 'type' is required");

            Class<?> elementCls = ClassUtils.getClass(typeName);
            return BeanMetaManager.getBeanMeta(elementCls);
        }

        ElementType elementType = this.metaType.getElementType(name);

        if (elementType == null) {
            throw new IllegalArgumentException("element '" + name + "' not found in '" + this.metaType.getName() + "'");
        }

        return elementType.getDataObjectMeta();
    }

    @Override
    public boolean writeClassName() {
        return false;
    }

}
